import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { KnowledgeEntity } from './knowledge.entity';
import { CreateKnowledgeDto, UpdateKnowledgeDto } from './dto';
import { CategoryEntity } from '../category/category.entity';

@Injectable()
export class KnowledgeService {
  constructor(
    @InjectRepository(KnowledgeEntity)
    private readonly knowledgeRepository: Repository<KnowledgeEntity>,
    @InjectRepository(CategoryEntity)
    private readonly categoryRepository: Repository<CategoryEntity>,
  ) {}

  async create(createKnowledgeDto: CreateKnowledgeDto): Promise<KnowledgeEntity> {
    const { rawHtml, categoryId } = createKnowledgeDto;

    const knowledge = new KnowledgeEntity();
    knowledge.rawHtml = rawHtml;

    if (categoryId) {
      const category = await this.categoryRepository.findOne({ where: { id: categoryId } });
      if (!category) {
        throw new NotFoundException(`分类ID ${categoryId} 不存在`);
      }
      knowledge.category = category;
    }

    return this.knowledgeRepository.save(knowledge);
  }

  async findAll(): Promise<KnowledgeEntity[]> {
    return this.knowledgeRepository.find({
      relations: ['category'],
    });
  }

  async findOne(id: number): Promise<KnowledgeEntity> {
    const knowledge = await this.knowledgeRepository.findOne({
      where: { id },
      relations: ['category'],
    });

    if (!knowledge) {
      throw new NotFoundException(`ID为 ${id} 的知识不存在`);
    }

    return knowledge;
  }

  async findByCategoryId(categoryId: number): Promise<KnowledgeEntity[]> {
    const category = await this.categoryRepository.findOne({ where: { id: categoryId } });
    if (!category) {
      throw new NotFoundException(`分类ID ${categoryId} 不存在`);
    }

    return this.knowledgeRepository.find({
      where: {
        category: { id: categoryId },
      },
      relations: ['category'],
    });
  }

	async findByCategoryIdAsHtml(categoryId: number): Promise<string> {
		const knowledgeList = await this.findByCategoryId(categoryId);

		if (knowledgeList.length === 0) {
      return `
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>知识列表</title>
          <style>
            body { font-family: Arial, sans-serif; margin: 20px; }
            .no-data { text-align: center; color: #666; }
          </style>
        </head>
        <body>
          <h1>知识列表</h1>
          <div class="no-data">暂无知识内容</div>
        </body>
        </html>
      `;
    }

    const htmlContent = knowledgeList.map(knowledge => knowledge.rawHtml).join('\n');

    return `
      <!DOCTYPE html>
      <html lang="zh-CN">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>知识列表 - ${knowledgeList[0]?.category?.name || '未分类'}</title>
        <style>
          body {
            font-family: Arial, sans-serif;
            margin: 20px;
            line-height: 1.6;
          }
          .knowledge-item {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: #f9f9f9;
          }
          h1 {
            color: #333;
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
          }
        </style>
      </head>
      <body>
        <h1>知识列表 - ${knowledgeList[0]?.category?.name || '未分类'}</h1>
        ${knowledgeList.map((knowledge, index) => `
          <div class="knowledge-item">
            <h3>知识 ${index + 1}</h3>
            ${knowledge.rawHtml}
          </div>
        `).join('')}
      </body>
      </html>
    `;
  }

  async update(id: number, updateKnowledgeDto: UpdateKnowledgeDto): Promise<KnowledgeEntity> {
    const knowledge = await this.findOne(id);

    if (updateKnowledgeDto.rawHtml) {
      knowledge.rawHtml = updateKnowledgeDto.rawHtml;
    }

    if (updateKnowledgeDto.categoryId) {
      const category = await this.categoryRepository.findOne({
        where: { id: updateKnowledgeDto.categoryId },
      });

      if (!category) {
        throw new NotFoundException(`分类ID ${updateKnowledgeDto.categoryId} 不存在`);
      }

      knowledge.category = category;
    }

    return this.knowledgeRepository.save(knowledge);
  }

  async remove(id: number): Promise<void> {
    const knowledge = await this.findOne(id);
    await this.knowledgeRepository.remove(knowledge);
  }
}
